new关键字的作用
new关键字创建实例的过程
1)创建一个新对象
2)将构造函数的作用域赋给新对象
3)执行构造函数中的代码
4)返回新对象
对于每一个实例,都会从原型上复制出一份一模一样的内存.
var F = function(){}; Object.prototype.a = function(){}; Function.prototype.b = function(){}; var f = new F();
new的过程拆解:
1)var f={}; 也就是说,初始化一个对象p。
2) f.__proto__=F.prototype;
3)F.call(f);也就是说构造p,也可以称之为初始化p。
console.log(f.__proto__===F.prototype); // 返回值为true,证明第2点
console.log(F.__proto__===Function.prototype); // 返回值为true
console.log(F.prototype.__proto__===Object.prototype); // 返回值为true
重点部分:console.log(f.__proto__.__proto__===Object.prototype); // 返回值为true
var animal = function(name){ this.name = name; }; animal.prototype.eat = function(){ console.log('animal eat!'); }; var cat = new animal('cat'); cat.eat(); // animal eat! cat.eat = function (){ console.log('cat eat!'); }; cat.eat();//cat eat! var dog = new animal('cat'); dog.eat();// animal eat!
如试例代码,对实例cat的eat方法的修改并未影响到原型以及其他实例。
function Person(){ this.type = 'human'; } Person.prototype.say = function(){ console.log('person say!'); }; var F = function(){}; F.prototype = Person.prototype; function Student(name){ this.name = name; } Student.prototype = new F(); //Student.prototype.constructor = Student; var xiaoming = new Student('xiaoming'); xiaoming.say(); console.log(xiaoming.constructor === Student); // false console.log(Student.prototype.constructor === Student);// false console.log(F.prototype.constructor === F);// false console.log(xiaoming.constructor === F); // false console.log(Student.prototype.constructor === F); // false console.log(xiaoming.constructor === Person); // ture console.log(Student.prototype.constructor === Person); // ture console.log(F.prototype.constructor === Person); // ture
// 比较区别 function Person(){ this.type = 'human'; } Person.prototype.say = function(){ console.log('person say!'); }; var F = function(){}; F.prototype = Person.prototype; function Student(name){ this.name = name; } Student.prototype = new F(); Student.prototype.constructor = Student; var xiaoming = new Student('xiaoming'); xiaoming.say(); console.log(xiaoming.constructor === F); // false console.log(Student.prototype.constructor === F); // false console.log(F.prototype.constructor === F);// false console.log(xiaoming.constructor === Person); // false console.log(Student.prototype.constructor === Person); // false console.log(xiaoming.constructor === Student); // true console.log(Student.prototype.constructor === Student);// true console.log(F.prototype.constructor === Person); // ture
原型链的操作。整个过程的变化图如下:
默认
增加代码
F.prototype = Person.prototype;
增加代码
Student.prototype.constructor = Student;
参考文章:
1.f 能取到a,b 吗?原理是什么?